package dog

import (
	"sync"
	"time"
)

type Dog struct {
	name         string
	keep_time_to int64
	hunger_cycle int64
	id           int
	died         bool
	lastword     IDogLastWord
	mutex        sync.Mutex
}

func (this *Dog) GetDogName() string {
	return this.name
}

func (this *Dog) SetDogName(name string) {
	this.name = name
}

func (this *Dog) GetDogId() int {
	return this.id
}

func (this *Dog) setDogId(id int) {
	this.id = id
}

func (this *Dog) Feed() bool {
	this.mutex.Lock()
	defer this.mutex.Unlock()

	if this.died {
		return false
	}

	this.keep_time_to = time.Now().Unix() + this.hunger_cycle
	return true
}

func (this *Dog) SetHungerCycle(hc int64) {
	this.mutex.Lock()
	defer this.mutex.Unlock()

	if this.died {
		return
	}

	this.hunger_cycle = hc
}

func (this *Dog) GetHungerCycle() int64 {
	return this.hunger_cycle
}

func (this *Dog) SetLastWord(lastword IDogLastWord) {
	this.mutex.Lock()
	defer this.mutex.Unlock()

	if this.died {
		return
	}

	this.lastword = lastword
}

func (this *Dog) TryRun() bool {
	this.mutex.Lock()
	defer this.mutex.Unlock()

	if this.died {
		return false
	}

	this.died = this.keep_time_to < time.Now().Unix()
	if this.died && this.lastword != nil {
		this.lastword.Execute()
	}

	return this.died
}

func (this *Dog) GetLifeCycle() int64 {
	return this.keep_time_to - time.Now().Unix()
}

func (this *Dog) SpendLife() {
	life_cycle :=this.GetLifeCycle()
	if life_cycle > 0 {
		time.Sleep(time.Second * time.Duration(this.GetLifeCycle()))
	}

	if !this.IsDied() {
		this.TryRun()
	}
}

func (this *Dog) IsDied() bool {
	return this.died
}
